package com.carpedil.shirodemo.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.carpedil.shirodemo.common.annotation.RefreshFilterChain;
import com.carpedil.shirodemo.common.util.ResultVO;
import com.carpedil.shirodemo.system.model.Operator;
import com.carpedil.shirodemo.system.service.IOperatorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 前端控制器
 *
 * @author carpedil
 * @since 2021-01-05
 */
@Controller
@RequestMapping("/operator")
public class OperatorController {
  @Autowired IOperatorService operatorService;

  @GetMapping("/index")
  public String index() {
    return "/operator/operator-list";
  }

  @GetMapping
  public String add() {
    return "operator/operator-add";
  }

  /**
   * 跳转 功能权限 修改页(与新增同一页面)
   *
   * @param model model
   * @param operatorId operatorId
   * @return String
   */
  @GetMapping("/{operatorId}")
  public String update(Model model, @PathVariable("operatorId") Integer operatorId) {
    // mybatis-plus自带方法
    Operator operator = operatorService.getById(operatorId);
    model.addAttribute("operator", operator);
    return "operator/operator-add";
  }

  @GetMapping("/tree")
  @ResponseBody
  public ResultVO tree() {
    return ResultVO.success(operatorService.getAllMenuAndOperatorTree());
  }

  /**
   * getOperatorListByMenuId
   *
   * @param menuId menuId
   * @return ResultVO
   */
  @GetMapping("/list")
  @ResponseBody
  public ResultVO getOperatorListByMenuId(@RequestParam(required = false) Integer menuId) {
    List<Operator> operators =
        operatorService.list(new QueryWrapper<Operator>().eq("menu_id", menuId));
    return ResultVO.success(operators);
  }

  @RefreshFilterChain
  @PostMapping
  @ResponseBody
  public ResultVO addOperator(Operator operator) {
    operatorService.insert(operator);
    return ResultVO.success();
  }

  @RefreshFilterChain
  @PutMapping
  @ResponseBody
  public ResultVO updateOperator(Operator operator) {
    operatorService.updateOperator(operator);
    return ResultVO.success();
  }

  @RefreshFilterChain
  @DeleteMapping("/{operatorId}")
  @ResponseBody
  public ResultVO deleteOperator(@PathVariable("operatorId") Integer operatorId) {
    operatorService.deleteById(operatorId);
    return ResultVO.success();
  }
}
